package com.wsgxj.service.impl;

import com.wsgxj.domain.*;
import com.wsgxj.mapper.*;
import com.wsgxj.service.UploadService;
import com.wsgxj.util.DateUtil;
import com.wsgxj.util.ShiroUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;

import java.text.ParseException;
import java.util.*;

@Service
public class UploadServiceImpl implements UploadService {

    //企业基本信息
    @Autowired
    private QyEnterpriseMapper qyEnterpriseMapper;
    //企业营业收入
    @Autowired
    private QyIncomeMapper qyIncomeMapper;
    //企业利润
    @Autowired
    private QyProfitMapper qyProfitMapper;
    //镇街
    @Autowired
    private ZjTownBackStreetsMapper zjTownBackStreetsMapper;
    //镇街营业收入
    @Autowired
    private ZjIncomeMapper zjIncomeMapper;
    //镇街利润
    @Autowired
    private ZjProfitMapper zjProfitMapper;
    //行业分类
    @Autowired
    private HyIndustryMapper hyIndustryMapper;
    //用电量
    @Autowired
    private HyElectricityConsumptionMapper hyElectricityConsumptionMapper;

    //事务控制
    @Autowired
    private PlatformTransactionManager platformTransactionManager;
    @Autowired
    private TransactionDefinition transactionDefinition;

    private static final Log logger = LogFactory.getLog(UploadServiceImpl.class);

    @Override
    public String upload(Map<String,List<String[]>> datas) throws Exception {
        TransactionStatus transaction = platformTransactionManager.getTransaction(transactionDefinition);
        try {
            //全部企业表数据填充
            List<String[]> townBackStreetsList = datas.get("镇街");
            List<String[]> allList = datas.get("全部企业");
            List<String[]> clothList = datas.get("纺织服装");
            List<String[]> buildingMaterialsList = datas.get("建材");
            List<String[]> equipment = datas.get("装备");
            List<String[]> chemicals = datas.get("化工");
            /**
             * enterpriseList工作簿原名【2020年12月行业用电分类（电网）】修改为【行业分类用电量】
             */
            List<String[]> enterpriseList = datas.get("行业分类用电量");
            List<String[]> industrialPowerList = datas.get("工业用电量");
            if (allList == null && enterpriseList == null) {
                throw new Exception("没有所需表单");
            }
            //行业分类用电量
            if (enterpriseList != null){
                electricityAdd(enterpriseList);
            }else {
                logger.warn("行业分类用电表为空");
            }
            //工业用电量
            if (industrialPowerList != null){
                electricitySupplement(industrialPowerList);
            }else {
                logger.warn("工业用电量表为空");
            }
            //镇街
            if (townBackStreetsList != null){
                townBackStreetsAdd(townBackStreetsList);
            } else {
                logger.warn("镇街表为空");
            }
            //全部企业
            if (allList != null){
                allEnterpriseAdd(allList);
            }else {
                logger.warn("全部企业表为空");
            }
            //纺织服装
            if (clothList != null){
                supplement(clothList);
            }else {
                logger.warn("纺织服装表为空");
            }
            //建材
            if (buildingMaterialsList != null){
                supplement(buildingMaterialsList);
            }else {
                logger.warn("建材表为空");
            }
            //装备
            if (equipment != null){
                supplement(equipment);
            }else {
                logger.warn("装备表为空");
            }
            //化工
            if (chemicals != null){
                supplement(chemicals);
            }else {
                logger.warn("化工表为空");
            }

        } catch (Exception e) {
            platformTransactionManager.rollback(transaction);
            logger.error("数据持久化失败，开始回滚",e);
            throw e;
        }
        platformTransactionManager.commit(transaction);
        logger.info("全部数据添加成功");
        return "数据添加成功";
    }

    /**
     * @param data 需要持久化的数据(行业比重)
     * @throws ParseException
     */
    public void supplement(List<String[]> data) throws ParseException {
        Date time = null;
        for (int i = 0; i < data.size() - 1; i++) {
            String[] datas = data.get(i);
            if (i == 0){
                time = DateUtil.parseStringToDate(datas[0],DateUtil.DATE_PATTERN_DATE);
                continue;
            }
            if (i <= 2){
                continue;
            }
            QyEnterprise qyEnterprise = qyEnterpriseMapper.findByName(datas[1]);
            if (qyEnterprise == null){
               logger.warn("添加行业比重未找到对应企业");
            }
            String enterpriseId = qyEnterprise.getId();
            qyIncomeMapper.updateByTimeAndEnterpriseId(time,enterpriseId,Double.parseDouble(datas[8]));
            //logger.info("行业比重添加(修改)成功-----" + datas[1]);
        }
    }

    /**
     * 全部企业及营收 | 利润数据
     * @param allList
     * @throws ParseException
     */
    public void allEnterpriseAdd(List<String[]> allList) throws ParseException {
        Date date = null;
        for (int i = 0; i < allList.size() - 1; i++) {
            String[] alls = allList.get(i);
            if (i == 0){
                date = DateUtil.parseStringToDate(alls[0],DateUtil.DATE_PATTERN_DATE);
                continue;
            }
            if (i <= 2){
                continue;
            }
            QyEnterprise qyEnterprise = new QyEnterprise();
            //全部企业表主键
            String enterpriseId = UUID.randomUUID().toString();
            //利润表主键
            String profitId = UUID.randomUUID().toString();
            //营收表主键
            String incomeId = UUID.randomUUID().toString();

            QyProfit qyProfit = new QyProfit();
            QyIncome qyIncome = new QyIncome();
            //根据企业名称查询企业
            QyEnterprise enterprise = qyEnterpriseMapper.findByName(alls[1]);
            //设置外键
            if (enterprise != null){
                //logger.warn("企业已存在#####" +enterprise.getName());
                qyProfit.setEnterpriseId(enterprise.getId());
                qyIncome.setEnterpriseId(enterprise.getId());
            } else {
                qyEnterprise.setId(enterpriseId);
                //企业名称
                qyEnterprise.setName(alls[1]);
                //根据镇街名称获取镇街类
                ZjTownBackStreets townBackStreets = zjTownBackStreetsMapper.findByName(alls[2]);
                if (townBackStreets != null){
                    //设置企业关联镇街
                    qyEnterprise.setZjTownBackStreetsId(townBackStreets.getId());
                } else {
                   logger.warn("镇街数据不全，插入企业信息失败----" + qyEnterprise.getName());
                }
                //行业代码
                qyEnterprise.setIndustryCode(alls[3]);
                //创建时间
                qyEnterprise.setCreationTime(new Date());
                //创建用户id
                qyEnterprise.setCreationUserId((Long) ShiroUtil.getSessionAttribute("id"));
                //动态新增企业
                qyEnterpriseMapper.insertSelective(qyEnterprise);
                qyIncome.setEnterpriseId(enterpriseId);
                qyProfit.setEnterpriseId(enterpriseId);
                //logger.info("企业添加成功-----" + qyEnterprise.getName());
            }
            //营业收入
            qyIncome.setId(profitId);
            //本月收入
            qyIncome.setThisMonthIncome(Double.parseDouble(alls[4]));
            //去年同期收入
            qyIncome.setLastYearSameMonthIncome(Double.parseDouble(alls[5]));
            //本月对比去年同期增幅
            qyIncome.setMonthIncrease(Double.parseDouble(alls[6]));
            //本年累计
            qyIncome.setThisYearGrandTotal(Double.parseDouble(alls[7]));
            //去年累计
            qyIncome.setLastYearGrandTotal(Double.parseDouble(alls[8]));
            //本年累计对比去年同期增幅
            qyIncome.setYearIncrease(Double.parseDouble(alls[9]));
            //月份
            qyIncome.setTime(date);
            //根据日期和外键查询营收是否存在
            QyIncome inc = qyIncomeMapper.findByEnterpriseIdAndTime(qyIncome.getEnterpriseId(), qyIncome.getTime());
            if (inc != null){
                qyIncome.setId(inc.getId());
                //根据主键动态更新企业营收
                qyIncomeMapper.updateByPrimaryKeySelective(qyIncome);
                //logger.info("企业营收修改");
            } else {
                //新增企业营收
                qyIncomeMapper.insertSelective(qyIncome);
                //logger.info("企业营收新增");
            }
            //利润
            qyProfit.setId(incomeId);
            //本月收入
            qyProfit.setThisMonthProfit(Double.parseDouble(alls[10]));
            //去年同期收入
            qyProfit.setLastYearSameMonthProfit(Double.parseDouble(alls[11]));
            //本月对比去年同期增幅
            qyProfit.setMonthIncrease(Double.parseDouble(alls[12]));
            //本年累计
            qyProfit.setThisYearGrandTotal(Double.parseDouble(alls[13]));
            //去年累计
            qyProfit.setLastYearGrandTotal(Double.parseDouble(alls[14]));
            //本年累计对比去年同期增幅
            qyProfit.setYearIncrease(Double.parseDouble(alls[15]));
            //月份
            qyProfit.setTime(date);
            //根据日期和外键查询利润是否存在
            QyProfit pro = qyProfitMapper.findByEnterpriseIdAndTime(qyIncome.getEnterpriseId(), qyIncome.getTime());
            if (pro != null){
                qyProfit.setId(pro.getId());
                //根据主键动态更新企业利润
                qyProfitMapper.updateByPrimaryKeySelective(qyProfit);
                //logger.info("企业利润修改");
            } else {
                //新增企业利润
                qyProfitMapper.insertSelective(qyProfit);
                //logger.info("企业利润新增");
            }
        }
    }

    /**
     * 镇街及营收 | 利润数据
     * @param townBackStreetsList
     * @throws ParseException
     */
    public void townBackStreetsAdd(List<String[]> townBackStreetsList) throws ParseException {
        Date date = null;
        for (int i = 0; i < townBackStreetsList.size() - 1; i++) {
            String[] alls = townBackStreetsList.get(i);
            if (i == 0) {
                date = DateUtil.parseStringToDate(alls[0], DateUtil.DATE_PATTERN_DATE);
                continue;
            }
            if (i <= 2){
                continue;
            }
            ZjTownBackStreets townBackStreets = new ZjTownBackStreets();
            //镇街表主键
            String townBackStreetsId = UUID.randomUUID().toString();
            //利润表主键
            String profitId = UUID.randomUUID().toString();
            //营收表主键
            String incomeId = UUID.randomUUID().toString();
            ZjProfit zjProfit = new ZjProfit();
            ZjIncome zjIncome = new ZjIncome();
            //根据镇街名称查询镇街
            ZjTownBackStreets zjTownBackStreets = zjTownBackStreetsMapper.findByName(alls[1]);
            //设置外键
            if (zjTownBackStreets != null) {
                //logger.warn("镇街已存在#####" +zjTownBackStreets.getName());
                zjIncome.setTownBackStreetsId(zjTownBackStreets.getId());
                zjProfit.setTownBackStreetsId(zjTownBackStreets.getId());
            } else {
                townBackStreets.setId(townBackStreetsId);
                //镇街名称
                townBackStreets.setName(alls[1]);
                zjTownBackStreetsMapper.insertSelective(townBackStreets);
                zjIncome.setTownBackStreetsId(townBackStreetsId);
                zjProfit.setTownBackStreetsId(townBackStreetsId);
                //logger.info("镇街添加成功-----" + townBackStreets.getName());
            }
            //营收
            zjIncome.setId(profitId);
            //本月收入
            zjIncome.setThisMonthIncome(Double.parseDouble(alls[2]));
            //去年同期收入
            zjIncome.setLastYearSameMonthIncome(Double.parseDouble(alls[3]));
            //本月对比去年同期增幅
            zjIncome.setMonthIncrease(Double.parseDouble(alls[4]));
            //本年累计
            zjIncome.setThisYearGrandTotal(Double.parseDouble(alls[5]));
            //全县占比
            zjIncome.setProportionTheCounty(Double.parseDouble(alls[6]));
            //去年累计
            zjIncome.setLastYearGrandTotal(Double.parseDouble(alls[7]));
            //本年累计对比去年同期增幅
            zjIncome.setYearIncrease(Double.parseDouble(alls[8]));
            //增幅位次
            zjIncome.setRank(Integer.parseInt(alls[9]));
            //月份
            zjIncome.setTime(date);
            //根据日期和外键查询营收是否存在
            ZjIncome ino = zjIncomeMapper.findByTownBackStreetsIdAndTime(zjIncome.getTownBackStreetsId(), zjIncome.getTime());
            if (ino != null){
                zjIncome.setId(ino.getId());
                //根据主键动态更新镇街营收
                zjIncomeMapper.updateByPrimaryKeySelective(zjIncome);
                //logger.info("镇街利润营收修改");
            } else {
                //动态插入镇街利润
                zjIncomeMapper.insertSelective(zjIncome);
                //logger.info("镇街营收新增");
            }
            //利润总额 zjProfit
            zjProfit.setId(incomeId);
            //本月收入
            zjProfit.setThisMonthProfit(Double.parseDouble(alls[10]));
            //去年同期收入
            zjProfit.setLastYearSameMonthProfit(Double.parseDouble(alls[11]));
            //本月对比去年同期增幅
            zjProfit.setMonthIncrease(Double.parseDouble(alls[12]));
            //本年累计
            zjProfit.setThisYearGrandTotal(Double.parseDouble(alls[13]));
            //全县占比
            zjProfit.setProportionTheCounty(Double.parseDouble(alls[14]));
            //去年累计
            zjProfit.setLastYearGrandTotal(Double.parseDouble(alls[15]));
            //本年累计对比去年同期增幅
            zjProfit.setYearIncrease(Double.parseDouble(alls[16]));
            //增幅位次
            zjProfit.setRank(Integer.parseInt(alls[17]));
            //月份
            zjProfit.setTime(date);
            //根据日期和外键查询利润是否存在
            ZjProfit pro = zjProfitMapper.findByTownBackStreetsIdAndTime(zjProfit.getTownBackStreetsId(), zjProfit.getTime());
            if (pro != null){
                zjProfit.setId(pro.getId());
                //根据id动态更新镇街利润数据
                zjProfitMapper.updateByPrimaryKeySelective(zjProfit);
                //logger.info("镇街利润修改");
            } else {
                //动态新增镇街利润数据
                zjProfitMapper.insertSelective(zjProfit);
                //logger.info("镇街利润新增");
            }
        }
    }

    /**
     * 所有行业用电量添加
     * @param enterpriseList
     */
    public void electricityAdd(List<String[]> enterpriseList) throws Exception {
        Date date = null;
        for (int i = 0; i < enterpriseList.size(); i++) {
            String[] enterprises = enterpriseList.get(i);
            if (i == 0){
                date = DateUtil.parseStringToDate(enterprises[0], DateUtil.DATE_PATTERN_DATE);
                continue;
            }
            if (i == 1){
                continue;
            }
            String electricityId = UUID.randomUUID().toString();
            HyElectricityConsumption hyElectricityConsumption = new HyElectricityConsumption();
            //行业分类外键设置
            HyIndustry hyIndustry = hyIndustryMapper.findByName(enterprises[1].trim());
            if (hyIndustry != null){
                logger.info(hyIndustry.getName() + "--用电量数据添加成功");
                hyElectricityConsumption.setIndustryId(hyIndustry.getId());
            }else{
                logger.error(enterprises[1] + "没找到对应");
                throw new Exception("行业分类用电量下第" + enterprises[0] + "行没有对应的行业分类");
            }
            //ID
            hyElectricityConsumption.setId(electricityId);
            //用户数
            hyElectricityConsumption.setNumberUsers(Integer.parseInt(enterprises[2]));
            //装接容量
            hyElectricityConsumption.setAssemblingCapacity(Integer.parseInt(enterprises[3]));
            //本月用电量
            hyElectricityConsumption.setThisMonthElectricity(Double.parseDouble(enterprises[4]));
            //上年同月用电量
            hyElectricityConsumption.setLastYearSameMonthElectricity(Double.parseDouble(enterprises[6]));
            //本月同比
            hyElectricityConsumption.setMonthIncrease(Double.parseDouble(enterprises[8]));
            //本年累计
            hyElectricityConsumption.setThisYearGrandTotal(Double.parseDouble(enterprises[9]));
            //去年累计
            hyElectricityConsumption.setLastYearGrandTotal(Double.parseDouble(enterprises[11]));
            //本年与上年增减值
            hyElectricityConsumption.setYearChange(Double.parseDouble(enterprises[12]));
            //本年同比
            hyElectricityConsumption.setYearIncrease(Double.parseDouble(enterprises[13]));
            //本月同比波动分析
            hyElectricityConsumption.setMonthIncreaseAnalysis(Double.parseDouble(enterprises[14]));
            //单位
            hyElectricityConsumption.setUnit(enterprises[18]);
            //口径
            hyElectricityConsumption.setCaliber(enterprises[19]);
            //行业编码
            hyIndustry.setIndustryCode(enterprises[20].trim());
            hyIndustryMapper.updateByPrimaryKey(hyIndustry);
            logger.info(hyIndustry.getName() + "----行业编码添加成功");
            //审核状态
            hyElectricityConsumption.setReviewStatus(enterprises[21]);
            //月份
            hyElectricityConsumption.setTime(date);
            HyElectricityConsumption ele = hyElectricityConsumptionMapper.findByTimeAndIndustryId(date, hyElectricityConsumption.getIndustryId());
            if (ele != null){
                hyElectricityConsumption.setId(ele.getId());
                //根据主键动态更新用电量
                hyElectricityConsumptionMapper.updateByPrimaryKeySelective(hyElectricityConsumption);
                logger.info("用电量修改成功");

            }else {
                //动态插入用电量数据
                hyElectricityConsumptionMapper.insertSelective(hyElectricityConsumption);
                logger.info("用电量新增成功");
            }
        }
    }

    /**
     * 所有行业用电量数据补充 | 全县比重
     * @param industrialPowerList
     */
    public void electricitySupplement(List<String[]> industrialPowerList) throws Exception {
        Date date = null;
        for (int i = 0; i < industrialPowerList.size(); i++) {
            String[] industrialPowers = industrialPowerList.get(i);
            if (i == 0) {
                date = DateUtil.parseStringToDate(industrialPowers[0], DateUtil.DATE_PATTERN_DATE);
                continue;
            }
            //标题列跳过
            if (i == 1) {
                continue;
            }
            //根据行业分类名称获取行业类
            HyIndustry hyIndustry = hyIndustryMapper.findByName(industrialPowers[1].trim());
            //判断行业分类是否存在（行业分类写死在数据库，暂未提供前端新增）
            if (hyIndustry == null){
                throw new Exception("工业用电量表下第" + industrialPowers[0] + "行没有对应的行业分类");
            }
            String industryId = hyIndustry.getId();
            //根据行业分类id、时间添加全县比重
            hyElectricityConsumptionMapper.updateByIndustryIdAndTime(industryId,date,industrialPowers[11]);
            logger.info(hyIndustry.getName() + "------全县比重添加成功");
        }
    }

}
